//
//  RCFeedbackVC.m
//  RocketProject
//
//  Created by Wu Chengwei on 13-6-23.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCFeedbackVC.h"
#import "UIColor-Expanded.h"
#import "CommonDefines.h"
#import "AppDelegate.h"
#import "GloableEngineService.h"
#import "RCFeedbackDataModel.h"

#define kTagFeedbackTextView        101
#define kTagPhoneTextView           102

#define kMaxWordCount               140

#define kFeedBackHolderString       @"感谢您使用如意行，请输入您的意见!"
#define kPhoneHolderString          @"请输入您的手机号码（选填）"

#define kPhoneImageFile             @"image_feedback_phone.png"
#define kSendImageFile              @"image_feedback_send.png"
#define kDotImageFile               @"image_feedback_dotline.png"
#define kLineImageFile              @"image_feedback_line.png"

#define kFeedbackViewFrame          CGRectMake(0,0,320,224)
#define kFeedbackTextViewFrame      CGRectMake(14,17,292,160)
#define kWordCountLabelFrame        CGRectMake(280,155,25,12)
#define kPhoneImageFrame            CGRectMake(14,193,10,18)
#define kPhoneTextViewFrame         CGRectMake(19,188,195,20)
#define kDotLineViewFrame           CGRectMake(209,186,1,32)
#define kSendButtonFrame            CGRectMake(236,181,48,42)
#define kSendImageViewFrame         CGRectMake(0,13,16,16)
#define kSendLabelFrame             CGRectMake(20,15,24,12)

@interface RCFeedbackVC ()

@property(nonatomic,retain) UIView *feedbackView;
@property(nonatomic,retain) UITextView *feedbackTextView;
@property(nonatomic,retain) UITextView *phoneTextView;
@property(nonatomic,retain) UIButton *sendButton;
@property(nonatomic,retain) UILabel *sendLabel;
@property(nonatomic,retain) UILabel *wordCountLabel;
@property(nonatomic,assign) int64_t requestID;

@end

@implementation RCFeedbackVC

@synthesize feedbackTextView = _feedbackTextView;
@synthesize feedbackView = _feedbackView;
@synthesize phoneTextView = _phoneTextView;
@synthesize sendButton = _sendButton;
@synthesize sendLabel = _sendLabel;
@synthesize wordCountLabel = _wordCountLabel;
@synthesize requestID = _requestID;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)dealloc{
    self.feedbackTextView.delegate = nil;
    self.feedbackTextView = nil;
    self.phoneTextView.delegate = nil;
    self.phoneTextView = nil;
    self.sendButton = nil;
    self.sendLabel = nil;
    self.feedbackView = nil;
    [super dealloc];
}

-(void)loadView{
    [super loadView];
    self.titleLabelText = @"意见反馈";
    self.navigationItem.titleView = [self createTitleView];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _feedbackView = [[UIView alloc]initWithFrame:kFeedbackViewFrame];
    _feedbackView.backgroundColor = [UIColor whiteColor];
    
    
    _feedbackTextView = [[UITextView alloc]initWithFrame:kFeedbackTextViewFrame];
    _feedbackTextView.tag = kTagFeedbackTextView;
    _feedbackTextView.backgroundColor = [UIColor clearColor];
    _feedbackTextView.delegate = self;
    _feedbackTextView.textColor = [UIColor colorWithHex:0xff979797];
    _feedbackTextView.font = [UIFont fontWithName:kFontNameLightHeiti size:12];
    [_feedbackTextView setReturnKeyType:UIReturnKeyDone];
    _feedbackTextView.text = kFeedBackHolderString;
    [_feedbackView addSubview:_feedbackTextView];
    
    _wordCountLabel = [[UILabel alloc]initWithFrame:kWordCountLabelFrame];
    _wordCountLabel.backgroundColor = [UIColor clearColor];
    _wordCountLabel.textColor = [UIColor colorWithHex:0xff979797];
    _wordCountLabel.font = [UIFont fontWithName:kFontNameHelvetica size:12];
    _wordCountLabel.text = @"140";
    [_feedbackView addSubview:_wordCountLabel];
    
    NSString *resourcePath = [[NSBundle mainBundle]resourcePath];
    UIImageView *upperLineView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 180, 320, 1)];
    NSString *linePath = [resourcePath stringByAppendingPathComponent:kLineImageFile];
    [upperLineView setImage:[UIImage imageWithContentsOfFile:linePath]];
    [_feedbackView addSubview:upperLineView];
    [upperLineView release];
    
    UIImageView *phoneImageView = [[UIImageView alloc]initWithFrame:kPhoneImageFrame];
    NSString *phonePath = [resourcePath stringByAppendingPathComponent:kPhoneImageFile];
    [phoneImageView setImage:[UIImage imageWithContentsOfFile:phonePath]];
    [_feedbackView addSubview:phoneImageView];
    [phoneImageView release];
    
    _phoneTextView = [[UITextView alloc]initWithFrame:kPhoneTextViewFrame];
    _phoneTextView.tag = kTagPhoneTextView;
    _phoneTextView.backgroundColor = [UIColor clearColor];
    _phoneTextView.delegate = self;
    _phoneTextView.textColor = [UIColor colorWithHex:0xff979797];
    _phoneTextView.font = [UIFont fontWithName:kFontNameLightHeiti size:12];
    [_phoneTextView setReturnKeyType:UIReturnKeyDone];
    _phoneTextView.text = kPhoneHolderString;
    [_feedbackView addSubview:_phoneTextView];
    
    UIImageView *dotImageView = [[UIImageView alloc]initWithFrame:kDotLineViewFrame];
    NSString *dotPath = [resourcePath stringByAppendingPathComponent:kDotImageFile];
    [dotImageView setImage:[UIImage imageWithContentsOfFile:dotPath]];
    [_feedbackView addSubview:dotImageView];
    [dotImageView release];
    
    _sendButton = [[UIButton alloc]initWithFrame:kSendButtonFrame];
    _sendButton.backgroundColor = [UIColor clearColor];
    _sendButton.enabled = NO;
    [_sendButton addTarget:self action:@selector(sendButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    UIImageView *sendImageView = [[UIImageView alloc]initWithFrame:kSendImageViewFrame];
    NSString *sendPath = [resourcePath stringByAppendingPathComponent:kSendImageFile];
    [sendImageView setImage:[UIImage imageWithContentsOfFile:sendPath]];
    [_sendButton addSubview:sendImageView];
    [sendImageView release];
    
    _sendLabel = [[UILabel alloc]initWithFrame:kSendLabelFrame];
    _sendLabel.backgroundColor = [UIColor clearColor];
//    _sendLabel.textColor = [UIColor colorWithHex:0xffff6900];
    _sendLabel.textColor = [UIColor colorWithHex:0xff979797];
    _sendLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:12];
    _sendLabel.text = @"发送";
    [_sendButton addSubview:_sendLabel];
    
    [_feedbackView addSubview:_sendButton];
    
    UIImageView *downLineImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 223, 320, 1)];
    [downLineImageView setImage:[UIImage imageWithContentsOfFile:linePath]];
    [_feedbackView addSubview:downLineImageView];
    [downLineImageView release];
    
    [self.viewContainer addSubview:_feedbackView];
    
	// Do any additional setup after loading the view.
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[IManager sharedInstance]cancelFetchDataRequestByRequestID:_requestID];
}

#pragma mark -
#pragma mark UITextView Delegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:kFeedBackHolderString] || [textView.text isEqualToString:kPhoneHolderString]) {
        textView.text=@"";
    }
    if (textView.tag == kTagPhoneTextView) {
        _phoneTextView.frame = CGRectMake(19,190,195,20);
        _phoneTextView.font = [UIFont fontWithName:kFontNameHelvetica size:12];
    }
    return YES;
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@""]) {
        if (textView.tag == kTagFeedbackTextView) {
            textView.text = kFeedBackHolderString;
        }else if (textView.tag == kTagPhoneTextView){
            textView.text = kPhoneHolderString;
            _phoneTextView.font = [UIFont fontWithName:kFontNameHeiti size:12];
        }
    }
}

- (void)textViewDidChange:(UITextView *)textView
{
    int length = 0;
    length = [textView.text length];
    if (textView.tag == kTagFeedbackTextView) {
        _sendButton.enabled = YES;
        _sendLabel.textColor = [UIColor colorWithHex:0xffff6900];
    }
    NSInteger restCount = kMaxWordCount - length;
    _wordCountLabel.text = [NSString stringWithFormat:@"%d",restCount];
    if (length > kMaxWordCount) {
        _wordCountLabel.textColor = [UIColor redColor];
        _sendButton.enabled = NO;
        _sendLabel.textColor = [UIColor colorWithHex:0xff979797];
    }else if(length == 0){
        _wordCountLabel.textColor = [UIColor colorWithHex:0xff979797];
        _sendButton.enabled = NO;
        _sendLabel.textColor = [UIColor colorWithHex:0xff979797];
    }else{
        _wordCountLabel.textColor = [UIColor colorWithHex:0xff979797];
        _sendLabel.textColor = [UIColor colorWithHex:0xffff6900];
    }

}

-(void)sendButtonClicked{
    
    if (![[GloableEngineService sharedInstance]alertLoginViewIfUnlogin:self]) {
        return;
    }
    
    _sendButton.enabled = NO;
    NetworkStatus status = [GloableEngineService sharedInstance].netWorkStatus;
    if (status == kNotReachable) {
        [RCAppDelegate alertWithNetworkError];
        _sendButton.enabled = YES;
        return;
    }
    if (nil == _feedbackTextView.text || [_feedbackTextView.text isEqualToString:@""] || [_feedbackTextView.text isEqualToString:kFeedBackHolderString]) {
        [RCAppDelegate alertWithCustomizeString:@"没有输入任何意见哦！"];
        _sendButton.enabled = YES;
        return;
    }
    
    if (nil == _phoneTextView.text || [_phoneTextView.text isEqualToString:@""] || [_phoneTextView.text isEqualToString:kPhoneHolderString]) {
        [RCAppDelegate alertWithCustomizeString:@"没有输入手机号码哦！"];
        _sendButton.enabled = YES;
        return;
    }
    
    
    if (![_phoneTextView.text isEqualToString:@""] && ![_phoneTextView.text isEqualToString:kPhoneHolderString]) {
        NSError * error = NULL;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^1[34578]\\d{9}$" options:0 error:&error];
        NSTextCheckingResult * result = [regex firstMatchInString:_phoneTextView.text options:0 range:NSMakeRange(0, [_phoneTextView.text length])];
        if (!result || (regex.numberOfCaptureGroups + 1) != result.numberOfRanges) {
            [RCAppDelegate alertWithCustomizeString:@"手机号码输入格式错误哦！"];
            _sendButton.enabled = YES;
            return;
        }
    }
    
    NSString *content = @"";
    if (![_feedbackTextView.text isEqualToString:kFeedBackHolderString]) {
        content = _feedbackTextView.text;
    }
    
    NSString *phone = @"";
    if (![_phoneTextView.text isEqualToString:kPhoneHolderString]) {
        phone = _phoneTextView.text;
    }
    // 提示用户正在发布
    TSAlert *alertsStruct = [[[TSAlert alloc] init] autorelease];
    alertsStruct.alertMessage = @"正在提交...";
    alertsStruct.isDismissByClick = NO;
    alertsStruct.alertStyleCode = TSAlertViewStyleSubmittingCode;
    [RCAppDelegate.alertViewManager addAlertToArray:alertsStruct];
    _requestID = [[IManager sharedInstance]requestFeedback:content withPhone:phone withDelegate:self];
}

-(void)updateViewForSuccess:(IDataModel *)dataModel withRequestId:(int64_t)requestId{
    if (_requestID == requestId) {
        RCFeedbackDataModel *feedbackDataModel = (RCFeedbackDataModel *)dataModel;
        if (feedbackDataModel.errorNO == 0) {
            [self publishSuccessAlert];
            _sendButton.enabled = NO;
            [self performSelector: @selector(backButtonClicked) withObject: nil afterDelay: 2];
        }else{
            [self publishFailAlert];
            _sendButton.enabled = YES;
        }
    }
}

-(void)updateViewForError:(NSError *)errorInfo withRequestId:(int64_t)requestId{
    if (_requestID == requestId) {
        [self publishFailAlert];
        _sendButton.enabled = YES;
    }
}

- (void) publishSuccessAlert
{
    // finish published
    [RCAppDelegate.alertViewManager cancelSubmit];
    
    TSAlert *alertsStruct = [[[TSAlert alloc] init] autorelease];
    alertsStruct.alertMessage = @"提 交 成 功！";
    alertsStruct.isDismissByClick = YES;
    alertsStruct.alertStyleCode = TSAlertViewStyleSubmittedCode;
    [RCAppDelegate.alertViewManager addAlertToArray:alertsStruct];
}

-(void)backButtonClicked{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void) publishFailAlert
{
    [RCAppDelegate.alertViewManager cancelSubmit];///baidu/BaiduTraveliOS/trunk/BaiduTravel/Classes/Engine/MessageDefine/ServerError.m
    
    TSAlert *alertsStruct = [[[TSAlert alloc] init] autorelease];
    alertsStruct.alertMessage = @"提 交 失 败，请 检 查 网 络 稍 后 再 试";
    alertsStruct.isDismissByClick = YES;
    alertsStruct.alertStyleCode = TSAlertViewStyleNetworkNotReachSubmitErrCode;
    
    [RCAppDelegate.alertViewManager addAlertToArray:alertsStruct];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
